<template>
  <el-dialog
    :visible.sync="visible" custom-class="custom-dialog" append-to-body v-draggable="needDrag"
    :close-on-click-modal="false"
    v-bind="$attrs" v-on="$listeners"
  >
    <el-scrollbar wrap-style="overflow-x: hidden;" :style="{height: height}">
      <slot></slot>
    </el-scrollbar>
    <div v-if="showCancelButton || showConfirmButton" class="dialog-footer" slot="footer">
      <el-button v-if="showCancelButton" @click="clickClose">{{ cancelButtonText }}</el-button>
      <el-button v-if="showConfirmButton" :loading="saving" type="primary" @click="clickConfirm">{{ confirmButtonText }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import DialogMixin from '@/mixins/dialog-mixin'

export default {
  name: 'custom-dialog',
  inheritAttrs: false,
  props: {
    beforeConfirm: {
      type: Function,
      default () {
        return () => {
        }
      }
    },
    onConfirm: {
      type: Function,
      default () {
        return () => {
        }
      }
    },
    onClose: Function,
    height: {
      type: String,
      default: 'auto'
    },
    showCancelButton: {
      type: Boolean,
      default: true
    },
    showConfirmButton: {
      type: Boolean,
      default: true
    },
    cancelButtonText: {
      type: String,
      default: '取消'
    },
    confirmButtonText: {
      type: String,
      default: '保存'
    },
    needDrag: {
      type: Boolean,
      default: true,
    }
  },
  mixins: [DialogMixin],
  data () {
    return {
      saving: false
    }
  },
  methods: {
    clickClose () {
      if (this.onClose) {
        this.onClose()
      }
      this.close()
    },
    clickConfirm () {
      if (this.saving) return
      const ret = this.beforeConfirm()
      if (ret === false) {
        this.saving = false
        return
      }
      if (ret === true) {
        this.saving = true
        this.onConfirm(this.close).finally(() => {
          this.saving = false
        })
      }
      if (ret.then) {
        ret.then(() => {
          this.saving = true
          this.onConfirm(this.close).finally(() => {
            this.saving = false
          })
        }).catch(() => {
        })
      }
    }
  }
}
</script>

<style scoped>
  ::v-deep .custom-dialog .el-dialog__header {
    border-bottom: 1px solid #eeeeee;
  }
</style>
